package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConst;
import com.itheima.entity.Result;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName UserController
 * @Description: TODO
 * @Author 郑乾
 * @Date 2020-06-18
 * @Version V1.0
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Reference
    private UserService userService;

    //登录成功
    @RequestMapping("loginSuccess")
    public ModelAndView loginSucess() {
        log.debug("登录成功");
        return new ModelAndView("redirect:http://localhost:83/pages/main.html");
    }

    @RequestMapping("loginFail")
    public ModelAndView loginFail() {
        log.debug("登录失败");
        return new ModelAndView("redirect:http://localhost:83/login.html?message=loginFail");
    }

    @RequestMapping("getUsername")
    public Result getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        log.debug("结果:...." + principal.toString());
        if (principal instanceof User) {
            User user = (User) principal;
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }
}
